import 'package:flutter/cupertino.dart';
import 'package:flutter_widgets_pc/widgets/pullDown/entity/drop_down_option.dart';
import 'package:flutter_widgets_pc/widgets/pullDown/pull_down_menu.dart';

class PullDownMenuSimple<T extends DropDownOption> extends StatelessWidget {
  final List<List<T>> listData;
  final List<T> chosenData;
  final Function(T data, int index)? callBack;

  const PullDownMenuSimple(
      {super.key,
      required this.listData,
      required this.chosenData,
      this.callBack});

  @override
  Widget build(BuildContext context) {
    return PullDownMenu(
        isShowCustomWidget: (menuIndex) => false,
        initChosenData: _formatListData(chosenData),
        titleRender: (titleData) {
          return titleData['title'];
        },
        menuDataRender: (menuIndex) => _formatListData(listData[menuIndex]),
        menuItemRender: (p0) {
          return p0['title'];
        },
        isUseOverlay: true,
        isDataSame: (p0, p1) {
          if (p0 != null && p1 != null && p0['titleId'] == p1['titleId']) {
            return true;
          } else {
            return false;
          }
        },
        isSelfControlHeaderData: (index) => false,
        pullDownCallback: (p0, p1) {
          callBack?.call(_getDataFromFormat(p0, p1), p1);
        },
        searchResultCallback: (menuIndex, searchContent) {
          return _searchData(menuIndex, searchContent);
        });
  }

  _getDataFromFormat(dynamic data, int index) {
    List<T> list = listData[index];
    for (T t in list) {
      if (t.title == data['title'] && t.titleId == data['titleId']) {
        return t;
      }
    }
    return null;
  }

  _formatListData(List<T> data) {
    List<dynamic> list = [];
    for (T t in data) {
      list.add(_formatData(t));
    }
    return list;
  }

  _formatData(T data) {
    return {"title": data.title, "titleId": data.titleId};
  }

  _searchData(int index, String content) {
    List<T> data = listData[index];
    if (content.isEmpty) {
      return _formatListData(data);
    }
    List<dynamic> list = [];
    for (T t in data) {
      if (t.title!=null&&t.title!.isNotEmpty && t.title!.contains(content)) {
        list.add(_formatData(t));
      }
    }
    return list;
  }
}
